<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <script>
      function reactive(target) {
        const keys = Object.keys(target);
        for (let index = 0; index < keys.length; index++) {
          const key = keys[index];
          let val = target[key];
          Object.defineProperty(target, key, {
            enumerable: true,
            configurable: true,
            get() {
              console.log("get()");
              return val;
            },
            set(newVal) {
              console.log("set()");
              val = newVal;
            },
          });
        }
      }

      const person = {
        name: "jack",
      };

      const proxy = reactive(person);

      console.log(person.name); // 触发 get
      person.name = "rose"; // 触发 set
      console.log(person.name); // 触发 get

      // Object.defineProperty 方法存在问题：
      // 新增属性不是响应式（没法触发get、set）
      // Vue2中解决方案：Vue.$set(target, key, val)  this.$set(target, key, val)
      console.log(person.age);
      person.age = 18;
    </script>
  </body>
</html>
